Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Solution:

  1. /**
  2. * Definition for singly-linked list with a random pointer.
  3. * class RandomListNode {
  4. * int label;
  5. * RandomListNode next, random;
  6. * RandomListNode(int x) { this.label = x; }
  7. * };
  8. */
  9. public class Solution {
  10. public RandomListNode copyRandomList(RandomListNode head) {
  11. if (head == null) return null;
  12. Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
  13. // step 1. copy all the nodes
  14. RandomListNode node = head;
  15. while (node != null) {
  16. map.put(node, new RandomListNode(node.label));
  17. node = node.next;
  18. }
  19. // step 2. assign next and random pointers
  20. node = head;
  21. while (node != null) {
  22. map.get(node).next = map.get(node.next);
  23. map.get(node).random = map.get(node.random);
  24. node = node.next;
  25. }
  26. return map.get(head);
  27. }
  28. }